import pygame
import random
from enemy import Enemy
from config import *

class Level:
    def __init__(self, level_number, screen):
        self.level_number = level_number
        self.screen = screen
        self.enemies = []
        self.platforms = []
        self.trees = []  # 树木列表
        self.grass = []  # 草地列表
        self.victory_point = None
        self.background_color = SKY_BLUE  # 天蓝色背景
        
        # 创建平台
        self.create_platforms()
        
        # 生成森林元素
        self.create_forest_elements()
        
        # 生成敌人
        self.spawn_enemies()
        
        # 创建胜利点
        self.create_victory_point()
        
    def create_platforms(self):
        # 创建地面平台
        ground = pygame.Rect(0, SCREEN_HEIGHT - 40, WORLD_WIDTH, 40)
        self.platforms.append(ground)
        
        # 创建一些随机平台
        for _ in range(PLATFORM_COUNT):
            x = random.randint(50, WORLD_WIDTH - 100)
            y = random.randint(SCREEN_HEIGHT - 200, SCREEN_HEIGHT - 80)
            width = random.randint(80, 200)
            height = 20
            platform = pygame.Rect(x, y, width, height)
            self.platforms.append(platform)
    
    def create_forest_elements(self):
        # 创建树木
        for _ in range(20):
            x = random.randint(0, WORLD_WIDTH - TREE_WIDTH)
            y = SCREEN_HEIGHT - 40 - TREE_HEIGHT
            tree = pygame.Rect(x, y, TREE_WIDTH, TREE_HEIGHT)
            self.trees.append(tree)
            
        # 创建草地
        for _ in range(30):
            x = random.randint(0, WORLD_WIDTH - 30)
            y = SCREEN_HEIGHT - 40 - GRASS_HEIGHT
            width = random.randint(20, 40)
            grass = pygame.Rect(x, y, width, GRASS_HEIGHT)
            self.grass.append(grass)
    
    def spawn_enemies(self):
        # 根据关卡数生成敌人
        enemy_count = INITIAL_ENEMY_COUNT + self.level_number * 2
        for _ in range(enemy_count):
            # 在平台上生成敌人
            platform = random.choice(self.platforms[:-1])  # 选择除地面外的随机平台
            x = random.randint(platform.left, platform.right - 30)
            y = platform.top - 30
            
            # 确保敌人不在玩家初始位置附近
            while x > SCREEN_WIDTH//2 - 100 and x < SCREEN_WIDTH//2 + 100:
                x = random.randint(platform.left, platform.right - 30)
                
            # 随机选择敌人类型
            enemy_types = ["basic", "fast", "strong"]
            enemy_type = random.choice(enemy_types)
            enemy = Enemy(x, y, enemy_type)
            self.enemies.append(enemy)
    
    def create_victory_point(self):
        # 在世界的右侧创建胜利点
        x = WORLD_WIDTH - 100
        y = SCREEN_HEIGHT - 90  # 在地面上方
        self.victory_point = pygame.Rect(x, y, VICTORY_POINT_WIDTH, VICTORY_POINT_HEIGHT)
    
    def update(self, player):
        # 更新敌人
        for enemy in self.enemies[:]:  # 使用切片复制列表以避免在迭代时修改列表
            enemy.move_towards_player(player.x, player.y, self.platforms)
            enemy.update()  # 更新敌人状态（包括攻击特效）
            
            # 检查敌人是否被击败
            if enemy.health <= 0:
                self.enemies.remove(enemy)
    
    def check_collisions(self, player):
        # 检查玩家与敌人的碰撞
        # 使用空间分割优化碰撞检测
        for enemy in self.enemies[:]:
            # 首先检查粗略距离检测
            if abs(player.x - enemy.x) < 100 and abs(player.y - enemy.y) < 100:
                if player.rect.colliderect(enemy.rect):
                    # 玩家攻击敌人（仅在玩家攻击时且攻击矩形与敌人碰撞）
                    if player.is_attacking:
                        attack_rect = player.get_attack_rect()
                        if attack_rect.colliderect(enemy.rect):
                            defeated = enemy.take_damage(player.attack_power)
                            if defeated:
                                self.enemies.remove(enemy)
                                # 播放击败敌人音效
                    # 敌人攻击玩家
                    else:
                        enemy.attack_player(player)
    
    def check_victory(self, player):
        # 检查玩家是否到达胜利点且所有敌人都被击败
        if len(self.enemies) == 0 and self.victory_point and player.rect.colliderect(self.victory_point):
            return True
        return False
    
    def draw(self, screen, camera):
        # 绘制背景（天蓝色）
        screen.fill(self.background_color)
        
        # 绘制草地
        for grass in self.grass:
            grass_rect = camera.apply(grass)
            pygame.draw.rect(screen, GREEN, grass_rect)
        
        # 绘制树木
        for tree in self.trees:
            tree_rect = camera.apply(tree)
            # 树干
            trunk_rect = pygame.Rect(tree_rect.x + TREE_WIDTH//2 - 5, tree_rect.y + TREE_HEIGHT//3, 10, TREE_HEIGHT*2//3)
            pygame.draw.rect(screen, BROWN, trunk_rect)
            # 树冠
            pygame.draw.circle(screen, DARK_GREEN, (tree_rect.centerx, tree_rect.y + TREE_HEIGHT//3), TREE_WIDTH)
        
        # 绘制平台
        for platform in self.platforms:
            # 应用摄像机偏移
            platform_rect = camera.apply(platform)
            pygame.draw.rect(screen, GRAY, platform_rect)  # 灰色平台
            pygame.draw.rect(screen, (80, 80, 80), platform_rect, 2)  # 平台边框
        
        # 绘制胜利点
        if self.victory_point:
            # 应用摄像机偏移
            victory_rect = camera.apply(self.victory_point)
            pygame.draw.rect(screen, GOLD, victory_rect)  # 金色胜利点
            pygame.draw.rect(screen, (200, 150, 0), victory_rect, 3)  # 胜利点边框
            # 绘制胜利点标识（使用系统字体解决中文乱码问题）
            try:
                # 尝试使用系统中文字体
                from start_screen import StartScreen
                font = StartScreen.get_chinese_font(None, 24)
            except:
                # 如果无法获取系统字体，使用默认字体
                font = pygame.font.Font(None, 24)
            victory_text = font.render("胜利点", True, BLACK)
            text_rect = victory_text.get_rect(center=victory_rect.center)
            screen.blit(victory_text, text_rect)
        
        # 绘制敌人
        for enemy in self.enemies:
            enemy.draw(screen, camera)
        
        # 绘制关卡信息
        font = pygame.font.Font(None, 36)
        level_text = font.render(f"Level: {self.level_number}", True, WHITE)
        screen.blit(level_text, (10, 10))
        
        # 绘制剩余敌人数量
        enemy_count_text = font.render(f"Enemies: {len(self.enemies)}", True, WHITE)
        screen.blit(enemy_count_text, (10, 50))